<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Article Details</title>
  <style>
    body {
      font-family: 'Open Sans', sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
      color: #333;
    }

    .container {
      max-width: 800px;
      margin: 30px auto;
      padding: 20px;
      background-color: #fff;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      border-radius: 10px;
    }

    h1 {
      text-align: center;
      color: #35424a;
    }

    .article-details {
      margin-top: 20px;
      padding: 20px;
      background-color: #f9f9f9;
      border-radius: 6px;
    }

    .article-details div {
      margin-bottom: 10px;
      transition: all 0.3s ease;
    }

    .article-details div:hover {
      background-color: #f1f1f1;
    }

    .article-details strong {
      display: block;
      color: #35424a;
    }

    .article-content {
      white-space: pre-line;
      margin-top: 20px;
      padding: 15px;
      background-color: #eef;
      border: 1px solid #ddd;
      border-radius: 8px;
    }

    .article-content p {
      margin: 0;
    }

    button {
      background-color: #5cb85c;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    button:hover {
      background-color: #4cae4c;
    }

    .comments-section {
      margin-top: 30px;
      background-color: #f9f9f9;
      padding: 20px;
      border-radius: 6px;
    }

    .comment {
      border-bottom: 1px solid #e0e0e0;
      padding: 10px 0;
    }

    .comment:last-child {
      border-bottom: none;
    }

    .comment-author {
      font-weight: bold;
      color: #35424a;
    }

    .comment-content {
      margin-left: 10px;
    }

    .comment-time {
      font-size: 0.8em;
      color: #666;
    }

    .no-comments-message {
      text-align: center;
      color: #666;
      padding: 20px 0;
    }

    .comment-form {
      margin-top: 20px;
    }

    .comment-form textarea {
      width: 100%;
      padding: 10px;
      margin-bottom: 10px;
      border-radius: 5px;
      border: 1px solid #ccc;
      resize: vertical;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .container {
        width: 90%;
        margin: 20px auto;
      }
    }
  </style>
</head>
<body>
<div class="container">
  <h1>Article Details</h1>
  <div class="article-details">
    <div>
      <strong>ID:</strong> <span th:text="${article.id}"></span>
    </div>
    <div>
      <strong>Title:</strong> <span th:text="${article.title}"></span>
    </div>
    <div>
      <strong>Content:</strong>
      <div class="article-content" th:utext="${article.content}"></div>
    </div>
    <div>
      <strong>Tag Name:</strong> <span th:text="${article.tagName}"></span>
    </div>
    <div>
      <strong>Update Time:</strong> <span th:text="${article.updatetime}"></span>
    </div>
    <div>
      <strong>Likes:</strong> <span id="likeCount" th:text="${article.likes}"></span>
    </div>
    <div>
      <strong>Comments:</strong> <span th:text="${article.comments}"></span>
    </div>
  </div>
  <div class="container">

    <div class="article-details">
      <!-- 省略其他文章详情 -->
      <div>
        <form method="post" style="display: inline;">
          <input type="hidden" name="articleId" th:value="${article.id}" />
          <button type="submit" class="btn-like"
                  th:class="${likes != null and likes.status == 1} ? 'liked' : ''"
                  th:text="${likes != null and likes.status == 1} ? '取消点赞' : '点赞'"
                  th:attr="data-url=@{/articlesLike/like(articleId=${article.id})}"
                  data-article-id="${article.id}"
                  onclick="likeArticle(this)">
          </button>
        </form>
      </div>
    </div>
  <!-- 评论区 -->
  <div class="comments-section">
    <h3>评论</h3>
    <div id="commentsList">
      <!-- 循环显示每条评论 -->
      <div th:each="comment : ${comments}" class="comment">
        <span class="comment-author" th:text="${comment.username} + ':'"></span>
        <span class="comment-content" th:text="${comment.content}"></span>
      </div>
    </div>
    <!-- 如果没有评论，则显示暂无评论 -->
    <div class="no-comments-message" th:if="${#lists.isEmpty(comments)}">暂无评论</div>

    <!-- 发表评论的表单 -->
    <div class="comment-form">
      <textarea id="commentText" rows="4" placeholder="写下你的评论..."></textarea>
      <!-- 提交按钮，使用th:attr绑定URL和调用JavaScript函数 -->
      <button id="submitCommentBtn" th:attr="data-url=@{/comments(article_id=${article.id})}" onclick="submitComment(this)">提交</button>
    </div>
  </div>
</div>
</div>
<script>
  function likeArticle(button) {
    var url = button.getAttribute('data-url');
    fetch(url, {
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: 'articleId=' + encodeURIComponent(button.getAttribute('data-article-id'))
    })
            .then(response => response.json())
            .then(data => {
              if (data.success) {
                // 更新点赞按钮的状态
                if (button.classList.contains('liked')) {
                  button.textContent = '点赞';
                  button.classList.remove('liked');
                } else {
                  button.textContent = '取消点赞';
                  button.classList.add('liked');
                }

                var likeCount = document.getElementById('likeCount');
                likeCount.textContent = parseInt(likeCount.textContent) + (data.liked ? -1 : 1);
                alert(likeCount);
              } else {
                // 提供默认错误消息
                var errorMessage = data.message ? data.message : '操作失败，请重试';
                alert(errorMessage);
              }
            })
            .catch(error => console.error('Error:', error));
  }

  function submitComment(button) {
    const commentText = document.getElementById('commentText').value;
    var url = button.getAttribute('data-url'); // 您需要将文章 ID 从服务器传递到 JavaScript
    if (!commentText.trim()) {
      alert("评论内容不能为空！");
      return;
    }

    // 使用 fetch API 提交评论
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({content: commentText})
    })
            .then(response => response.json())
            .then(data => {
              if (data.success) {
                // 清空评论框
                document.getElementById('commentText').value = '';

                // 更新评论列表
                const commentsList = document.getElementById('commentsList');
                const newComment = document.createElement('div');
                newComment.className = 'comment';
                newComment.innerHTML = `<span>${data.comment.username}：<span>${data.comment.content}</span></span>`;
                commentsList.appendChild(newComment);

                // 更新评论数
                const commentCount = document.getElementById('commentCount');
                commentCount.textContent = parseInt(commentCount.textContent) + 1;
                const noCommentsMessage = document.querySelector('.no-comments-message'); // 你需要给这个div一个类名
                if (noCommentsMessage) {
                  noCommentsMessage.style.display = 'none'; // 隐藏没有评论的提示
                }
              } else {
                alert(data.message || '评论提交失败，请重试。');
              }
            })
            .catch(error => {
              console.error('Error:', error);
            });
  }

  function goBack() {
    window.location.replace(document.referrer);
  }
</script>
</body>
</html>